﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crosland.Automotriz.Logic;
using System.Configuration;
using Crosland.Automotriz.Logic.Linq;
using System.Data;
using Crosland.Automotriz.Entidad;

namespace Crosland.Automotriz.Web.Vehiculos
{
    public partial class wFrmVentaExternaStockModeloActualizar : System.Web.UI.Page
    {
        string idNegocio = ConfigurationManager.AppSettings["Negocio"];
        const string script = "MostrarAlerta();";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false) 
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("DES_MARCA");
                dt.Columns.Add("ID_MODELO");
                dt.Columns.Add("DES_MODELO");
                dt.Columns.Add("STOCK");
                Session["dt"] = dt;

                ListarMarcas();
                cboMarca_SelectedIndexChanged(null, null);
                if(Request.QueryString["anio"] != null && Request.QueryString["mes"] != null)
                {
                    lblAnio.Text = Request.QueryString["anio"];
                    lblMes.Text = Request.QueryString["mes"];
                }

                ListarGrilla();
            }
        }

        void ListarMarcas()
        {
            clsTD_MarcaBL neg = new clsTD_MarcaBL();
            cboMarca.DataSource = neg.ListarMarcas();
            cboMarca.TextField = "DES_MARCA";
            cboMarca.ValueField = "ID_MARCA";
            cboMarca.DataBind();
            cboMarca.SelectedIndex = 0;
        }

        void ListarModelos() 
        {
            int id_marca = int.Parse(cboMarca.Value.ToString());
            clsTH_Venta_Externa_Stock_ModeloBL neg = new clsTH_Venta_Externa_Stock_ModeloBL();
            cboModelo.DataSource = neg.ListarModelosPorMarca(id_marca);
            cboModelo.TextField = "DES_MODELO";
            cboModelo.ValueField = "ID_MODELO";
            cboModelo.DataBind();
            cboModelo.SelectedIndex = 0;
        }

        void ListarGrilla() 
        {
            int anio = int.Parse(lblAnio.Text);
            int mes = int.Parse(lblMes.Text);
            string idUsuario = Session["User"].ToString();
        
            clsTH_Venta_Externa_Stock_ModeloBL neg = new clsTH_Venta_Externa_Stock_ModeloBL();
            List <TH_VENTA_EXTERNA_STOCK_MODELO_LISTAR> lista = neg.Listar(anio, mes, idUsuario);
            if (lista != null)
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["dt"];
                for (int i = 0; i < lista.Count; i++)
                {
                    DataRow dr;
                    dr = dt.NewRow();
                    dr[0] = lista[i].DES_MARCA;
                    dr[1] = lista[i].ID_MODELO;
                    dr[2] = lista[i].DES_MODELO;
                    dr[3] = lista[i].STOCK;
                    dt.Rows.Add(dr);

                    Session["dt"] = dt;
                    gv.DataSource = dt;
                    gv.DataBind();
                }
            }
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Vehiculos/wFrmVentaExternaStockModelo.aspx?id=" + idNegocio);
        }

        protected void btnGrabar_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["dt"];
                clsTH_Venta_Externa_Stock_ModeloBL neg = new clsTH_Venta_Externa_Stock_ModeloBL();
                int ID_VENTA_EXTERNA_STOCK_MODELO = 0;
                int ID_MODELO, ANIO, MES, STOCK;
                string idUsuario = Session["User"].ToString();
                ANIO = int.Parse(lblAnio.Text);
                MES = int.Parse(lblMes.Text);
                //Eliminar
                neg.Eliminar(idUsuario, ANIO, MES);
                //Registrar
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ID_VENTA_EXTERNA_STOCK_MODELO = neg.UltimoID() + 1;
                    ID_MODELO = int.Parse(dt.Rows[i]["ID_MODELO"].ToString());

                    STOCK = int.Parse(dt.Rows[i]["STOCK"].ToString());
                    neg.Insertar(ID_VENTA_EXTERNA_STOCK_MODELO, ID_MODELO, ANIO, MES, STOCK, idUsuario);
                }
                btnGrabar.Enabled = false;
                cboMarca.Enabled = false;
                cboModelo.Enabled = false;
                seStock.Enabled = false;
                btnAgregar.Enabled = false;
                gv.Enabled = false;

                lblMensaje.Text = "Datos registrados satisfactoriamente";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
            }
            catch (Exception ex)
            {
                lblMensaje.Text = ex.Message;
                ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
            }
        }

        protected void cboMarca_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListarModelos();
        }

        protected void btnAgregar_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["dt"];

                if (int.Parse(seStock.Value.ToString()) <= 0)
                {
                    lblMensaje.Text = "Debe ingresar un valor mayor a cero.";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
                    seStock.Focus();
                    return;
                }

                bool repetido = false;
                //Validar que no se repitan los modelos
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["ID_MODELO"].ToString() == cboModelo.Value.ToString())
                    {
                        repetido = true;
                    }
                }

                if (repetido == true)
                {
                    lblMensaje.Text = "Este modelo ya se encuentra en la lista.";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
                    cboModelo.Focus();
                    return;
                }

                DataRow dr;
                dr = dt.NewRow();
                dr[0] = cboMarca.Text;
                dr[1] = int.Parse(cboModelo.Value.ToString());
                dr[2] = cboModelo.Text;
                dr[3] = int.Parse(seStock.Value.ToString());
                dt.Rows.Add(dr);

                Session["dt"] = dt;
                gv.DataSource = dt;
                gv.DataBind();

                seStock.Number = 1;
            }
            catch (Exception ex)
            {
                lblMensaje.Text = ex.Message;
                ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
            }
        }

        protected void gv_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["dt"];

                int id_modelo = int.Parse(e.Keys[0].ToString());

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["ID_MODELO"].ToString() == id_modelo.ToString())
                    {
                        dt.Rows.RemoveAt(i);
                        break;
                    }
                }

                e.Cancel = true;

                Session["dt"] = dt;
                gv.DataSource = dt;
                gv.DataBind();

            }
            catch (Exception ex)
            {
                lblMensaje.Text = ex.Message;
                ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
            }
        }
    }
}